<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
           <el-row :gutter="20">
               <el-col :span="8">
                    <el-input placeholder="请输入内容"  class="input-with-select" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
               </el-col>
               <el-col :span="4">
                   <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
               </el-col>
           </el-row>
           <el-table :data="userList" border >
               <el-table-column type="index" width="50" label="#" align="center"></el-table-column>
               <el-table-column label="姓名" prop="username" align="center"></el-table-column>
               <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
               <el-table-column label="电话" prop="mobile" align="center"></el-table-column>
               <el-table-column label="角色" prop="role_name" align="center"></el-table-column>
               <el-table-column label="状态" align="center">
                   <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" active-color="#13ce66" @change="userStateChange(scope.row)">
                        </el-switch>
                   </template>
               </el-table-column>
               <el-table-column label="操作" width="190px">
                   <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini"  @click="openDeleteDilog(scope.row.id)"></el-button>
                         <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                   </template>
               </el-table-column>
           </el-table>
               <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 3, 4]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
        </el-card>
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="restForm">
              <el-form  :model="addForm" :rules="addRules" ref="addRef" label-width="100px" inline-message>
                <el-form-item prop="username" label="用户名" >
                    <el-input prefix-icon="el-icon-user" v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input prefix-icon="el-icon-goods" show-password v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                    <el-input prefix-icon="el-icon-goods" v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item prop="mobile" label="手机">
                    <el-input prefix-icon="el-icon-goods" v-model.number="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible=false">取 消</el-button>
            <el-button type="primary" @click="dealAdduser">确 定</el-button>
        </span>
        </el-dialog>
               <el-dialog title="修改用户" :visible.sync="editDilog" width="50%" @close="restEditForm">
              <el-form  :model="editForm" :rules="editRules" ref="editRef" label-width="100px" inline-message>
                <el-form-item label="用户名" >
                    <el-input prefix-icon="el-icon-user" v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                    <el-input prefix-icon="el-icon-goods" v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item prop="mobile" label="手机">
                    <el-input prefix-icon="el-icon-goods" v-model.number="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDilog=false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default { 
        data() {
            /* 自定义验证手机规则 */
            var checkMobile = (rule, value, callback) => {
                            const numbers = /[0-9]{11}/
                            if (!numbers.test(value)) {
                               return callback(new Error('手机号必须为11位数字'))
                            }
                            /* 一定要调用回调函数，不然验证是不返回数据 */
                            callback()
            }
            return {
                queryInfo: { query: '', pagenum: 1, pagesize: 4 },
                userList: [],
                total: 0,
                dialogVisible: false,
                /* 添加用户数据 */
                addForm: { username: '', password: '', email: '', mobile: '' },
                addRules: {
                        username: [
                            { required: true, message: '请输入用户名', trigger: 'blur' },
                            { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
                        ],
                        password: [
                            { required: true, message: '请输入密码', trigger: 'blur' },
                            { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
                        ],
                        email: [
                            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                        ],
                        mobile: [
                            { validator: checkMobile, message: '请输入正确的手机号', trigger: 'blur' }
                        ]
                },
                editDilog: false,
                editForm: { username: '', email: '', mobile: '' },
                editRules: {
                       email: [
                            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                        ],
                        mobile: [
                            { validator: checkMobile, message: '请输入正确的手机号', trigger: 'blur' }
                        ]
                }
            }
        },
        created() {
            this.getUserList()
        },
        methods: {
            async getUserList() {
                const result = await this.$http.get('users', { params: this.queryInfo })
                const res = result.data
                if (res.meta.status !== 200) {
                     return this.$message.error('用户获取失败')
                }
                this.userList = res.data.users
                this.total = res.data.total
            },
            handleSizeChange(val) {
                this.queryInfo.pagesize = val
                this.getUserList()
            },
            handleCurrentChange(val) {
                this.queryInfo.pagenum = val
                this.getUserList()
            },
            /* 监听用户状态switch开关 */
            async userStateChange(userinfo) {
                const result = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
                const res = result.data
                if (res.meta.status !== 200) {
                    /* 更新失败 重置原样 */
                    userinfo.mg_state = !userinfo.mg_state
                    return this.$message.error('用户状态改变失败')
                }
                this.$message.success('用户状态改变成功')
            },
            dealAdduser: function() {
                this.$refs.addRef.validate( async valid => {
                    if (!valid) return 
                    const result = await this.$http.post('users', this.addForm)
                    const res = result.data
                    console.log(res)
                    if (res.meta.status !== 201) return this.$message.error('添加用户失败')
                    this.$message.success('添加用户成功')
                })
                this.dialogVisible = false
            },
            /* 监听对话框关闭时 重置表单的验证提示 */
            restForm() {
                this.$refs.addRef.resetFields()
            },
            async showEditDialog(id) {
                const result = await this.$http.get('users/' + id)
                const res = result.data
                if (res.meta.status !== 200) return this.$message.error('用户信息查询失败') 
                this.editForm = res.data
                this.editDilog = true
            },
            /* 重置编辑用户dilog状态 */
            restEditForm() {
                this.$refs.editRef.resetFields()
            },
            editUser() {
                this.$refs.editRef.validate(async valid => {
                    if (!valid) return this.$message.error('用户信息验证失败')
                    const result = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
                    const res = result.data
                    console.log(this.editForm.id)
                    if (res.meta.status !== 200) return this.$message.error('用户信息更新失败')
                    this.editDilog = false
                    this.getUserList()
                    this.$message.success('用户信息更新成功')
                })
            },
            /* 弹出确认删除框 */
             async openDeleteDilog(id) {
                const confirmRes = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).catch(err => err)
                if (confirmRes !== 'confirm') {
                    return this.$message.info('已取消删除')
                }
                const result = await this.$http.delete('users/' + id)
                const res = result.data
                if (res.meta.status !== 200) return this.$message.error('用户删除失败')
                this.$message.success('用户删除成功')
                this.getUserList()
            }
        }
    }
</script>
<style scoped>
    .el-input--prefix .el-input__inner {
        max-width:60%; 
    }
</style>
